package com.xunwulian.web.controller.buss;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.gson.Gson;
import com.xunwulian.api.dto.BaseResponse;
import com.xunwulian.api.iface.CardAPI;
import com.xunwulian.api.iface.ConfigAPI;
import com.xunwulian.api.iface.SmsAPI;
import com.xunwulian.base.constant.CommonErrorCode;
import com.xunwulian.base.entity.*;
import com.xunwulian.base.util.MyLogUtil;
import com.xunwulian.base.util.PageData;
import com.xunwulian.base.util.UserUtil;
import com.xunwulian.web.controller.BaseController;
import com.xunwulian.web.entity.SmsPocessorCountByUserEntityWrapper;
import com.xunwulian.web.util.AppUtil;
import com.xunwulian.web.util.Const;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/smspocessor")
public class SmsPocessorController extends BaseController {

    private String menuUrl = "smspocessor/list.do"; // 菜单地址(权限用)

    @Reference
    private SmsAPI smsAPI;
    @Reference
    private CardAPI cardAPI;
    @Reference
    private ConfigAPI configAPI;

    /**
     * 发短信
     *
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/goSend")
    public ModelAndView goSend() {

        ModelAndView mv = this.getModelAndView();

        List<String> hotList = new ArrayList<>();
        try {
            // 从session获取用户信息
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);
            String userId = user.getUSER_ID();

            hotList = (List<String>) smsAPI.getHostList(userId).getData();
            logger.debug("hotList:" + new Gson().toJson(hotList));

        } catch (Exception e) {
            e.printStackTrace();
        }

        mv.addObject("hotList", hotList);
        mv.setViewName("system/smspocessor/smspocessor");
        return mv;
    }

    /**
     * 发短信
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/doSend", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object doSend(@RequestParam("phone") String phone,
                         @RequestParam("content") String content) {

        Map<String, Object> map = new HashMap();

        try {
            logger.info(phone);
            logger.info(URLDecoder.decode(content, "utf8"));
            logger.info(URLDecoder.decode(URLDecoder.decode(content, "utf8"), "utf8"));

            map.put("code", CommonErrorCode.SUCCESS.getType());
            map.put("msg", "发送成功！");

            logger.debug("phone:" + phone + ", content:" + content);

            // 从session获取用户信息
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);
            String userId = user.getUSER_ID();

//        if (user.getBalance() - 0.0 < 0.0001) {
//            map.put("code", "0001");
//            map.put("msg", "余额不足!");
//        }

            // 数据校验
            List<String> msisdnList = Arrays.asList(phone.split(","));
            msisdnList.stream().distinct().forEach(p -> {

                String msisdn = StringUtils.trimAllWhitespace(p);

                CardInfoEntity cardInfoEntity = cardAPI.getByMsisdn(msisdn);

                if (cardInfoEntity == null) {

                    // 卡号不存在
                    logger.error("cardInfoEntity not exists, msisdn:" + msisdn);

                    map.put("code", CommonErrorCode.E_CARDINFO_NOT_EXISTS.getType());
                    map.put("msg", CommonErrorCode.E_CARDINFO_NOT_EXISTS.getDesc() + ", " + msisdn);

                } else if (!UserUtil.isAdmin(user.getROLE_ID())
                        && !UserUtil.isSubAdmin(user.getROLE_ID())
                        && !userId.equals(cardInfoEntity.getUserId())
                        && !userId.equals(cardInfoEntity.getSubUserId())) {

                    // 不在用户名下的卡，不允许发送，管理员不限制
                    logger.error("cardInfoEntity 不在用户名下, msisdn:" + msisdn);

                    map.put("code", CommonErrorCode.E_CARDINFO_AUTHOR.getType());
                    map.put("msg", CommonErrorCode.E_CARDINFO_AUTHOR.getDesc() + ", " + msisdn);

                } else if ((Integer) smsAPI.checkFrequence(userId, msisdn, content).getData() > 0) {

                    //最近发送过相同短信，提示错误
                    logger.error("三分钟发送过相同短信, msisdn:" + msisdn);

                    map.put("code", CommonErrorCode.E_SMS_FRENQUECE.getType());
                    map.put("msg", CommonErrorCode.E_SMS_FRENQUECE.getDesc());
                }
            });

            if (CommonErrorCode.SUCCESS.getType().equals(map.get("code"))) {

                logger.info("before unescape:" + content);
                final String contentSent = URLDecoder.decode(URLDecoder.decode(content, "utf8"), "utf8");
                logger.info("after unescape:" + contentSent);

                try {
                    // 发短信
                    msisdnList.stream().distinct().forEach(p -> {
                        String msisdn = StringUtils.trimAllWhitespace(p);
                        CardInfoEntity cardInfoEntity = cardAPI.getByMsisdn(msisdn);
                        logger.info("cardInfoEntity", new Gson().toJson(cardInfoEntity));
                        smsAPI.send(userId, p, contentSent, cardInfoEntity.getAppId());
                    });
                } catch (Exception e) {
                    logger.info("send message exception");
                    e.printStackTrace();
                    map.put("code", CommonErrorCode.E_SMS_API.getType());
                    map.put("msg", CommonErrorCode.E_SMS_API.getDesc());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return AppUtil.returnObject(new PageData(), map);
    }


    /**
     * 按用户统计短信发送列表
     *
     * @return
     */
    @RequestMapping(value = "/listByUser")
    public ModelAndView listByUser(Page page) {

        logBefore(logger, "列表SmsPocessor");
        ModelAndView mv = this.getModelAndView();

        try {
            // 从session获取用户信息
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);

            String userId = UserUtil.isAdmin(user.getROLE_ID()) || UserUtil.isSubAdmin(user.getROLE_ID()) ? "" : user.getROLE_ID();
            BaseResponse<List<SmsPocessorCountByUserEntity>> response = smsAPI.listPageStatByUser(page, userId, "");
            page = response.getPage();
            List<SmsPocessorCountByUserEntity> varList = response.getData(); // 列出SmsPocessor列表

            List<SmsPocessorCountByUserEntityWrapper> listWrapper = new ArrayList();
            varList.forEach(entity -> listWrapper.add(new SmsPocessorCountByUserEntityWrapper(entity)));

            mv.setViewName("system/smspocessor/smspocessor_listbyuser");

            mv.addObject("varList", listWrapper);
            mv.addObject("page", page);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mv;
    }

    /**
     * 列表
     *
     * @param page
     * @param msisdnKey
     * @param userNameKey
     * @param typeId
     * @return
     */
    @RequestMapping(value = "/list")
    public ModelAndView list(@Param("page") Page page,
                             @Param("msisdnKey") String msisdnKey,
                             @Param("userNameKey") String userNameKey,
                             @Param("typeId") Integer typeId) {

        ModelAndView mv = this.getModelAndView();
        try {
            logBefore(logger, "列表SmsPocessor");

            // 从session获取用户信息
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);

            // 管理员查询所有
            String userId = UserUtil.isAdmin(user.getROLE_ID()) || UserUtil.isSubAdmin(user.getROLE_ID()) ? "" : user.getUSER_ID();
            String appId = UserUtil.isSubAdmin(user.getROLE_ID()) ? user.getAppId() : "";

            BaseResponse<List<SmsPocessorEntity>> response = smsAPI.listPage(page,
                    appId,
                    userId,
                    msisdnKey,
                    userNameKey,
                    typeId);

            List<SmsPocessorEntity> varList = response.getData();
            page = response.getPage();

            // 特殊字符转义
            varList.stream().filter(p -> p.getContent().contains("<")).forEach(p -> p.setContent(p.getContent().replace("<", "&lt")));

            logger.info("varList:" + new Gson().toJson(varList));

            mv.setViewName("system/smspocessor/smspocessor_list");

            mv.addObject("varList", varList);
            mv.addObject("msisdnKey", msisdnKey);
            mv.addObject("userNameKey", userNameKey);
            mv.addObject("page", page);

            mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mv;
    }

    public Map<String, String> getHC() {
            Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }

    /**
     * 获取最常用短信
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getHotestSmsList")
    @ResponseBody
    public Object getHotestSmsList(@RequestParam("userId") String userId) {

        List<String> hotList = new ArrayList<>();
        Map<String, Object> map = new HashMap();

        try {
            hotList = (List<String>) smsAPI.getHostList(userId).getData();

            map.put("code", "0000");
            map.put("msg", "success");
            map.put("hotList", hotList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format,
                true));
    }
}
